import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";


enum AssociatedType {
  room,
  public
}

enum DeviceType {
  lock,
  electricityMeter,
  faceLock,
}
class AssociateUnbindDevices extends StatefulWidget {
  final AssociatedType type;
  final DeviceType deviceType;
  final int roomId;
  final String roomName;
  final String buildingName;
  const AssociateUnbindDevices({super.key, required this.type, required this.roomId, required this.roomName, required this.deviceType, required this.buildingName});

  @override
  State<StatefulWidget> createState() => _AssociateUnbindDevicesState();

}

class _AssociateUnbindDevicesState extends State<AssociateUnbindDevices> {

  List _list = [];
  int _checkIndex = -1;

  ///标题
  String _title() {
    String associatedName = "";
    String deviceName = "";
    if (widget.type == AssociatedType.room) {
      associatedName = "房间";
    } else {
      associatedName = "公区";
    }
    switch (widget.deviceType) {
      case DeviceType.lock:
        deviceName = "锁";
        break;
      case DeviceType.electricityMeter:
        deviceName = "电表";
        break;
      case DeviceType.faceLock:
        deviceName = "门禁";
    }
    return "关联$associatedName$deviceName";
  }

  String _name(Map item) {
    String name = "";
    switch (widget.deviceType) {
      case DeviceType.lock:
        name = item["lockName"];
        break;
      case DeviceType.electricityMeter:
        name = item["name"];
        break;
      case DeviceType.faceLock:
        name = item["faceLockName"];
    }
    return name;
  }

  void _getUnbindList() async {
    EasyLoading.show();

    Map resData;
    dynamic params;
    switch (widget.deviceType) {
      case DeviceType.lock:
        resData = await lockApi.unbindList();
        break;
      case DeviceType.electricityMeter:
        resData = await electricityMeterApi.unbindList();
        break;
      case DeviceType.faceLock:
        params = widget.roomId;
        resData = await entranceGuardApi.unbindList(params);
    }

    setState(() {
      _list = resData["data"] ?? [];
    });
    EasyLoading.dismiss();
  }



  void _bindDevice() async {
    String tip = "";
    switch (widget.deviceType) {
      case DeviceType.lock: ///门锁
        tip = "智能锁：${_list[_checkIndex]["lockName"]}";
        break;
      case DeviceType.electricityMeter: ///电表
        tip = "电表：${_list[_checkIndex]["name"]}";
        break;
      case DeviceType.faceLock: /// 门禁
        tip = "电表：${_list[_checkIndex]["faceLockName"]}";
        break;
    }
    tip += "，将关联到房间：${widget.roomName}";
    taiDialog(
      context: context,
      child: Text(tip, textAlign: TextAlign.center,),
      onConfirm: (taiContext) async {
        Navigator.of(taiContext).pop();
        EasyLoading.show();
        Map<String, dynamic> params = {
          "roomId": widget.roomId,
        };
        Map<String, dynamic> editNameParams = {};
        switch (widget.deviceType) {
          case DeviceType.lock:

          ///门锁
            params["lockId"] = _list[_checkIndex]["lockId"];
            await lockApi.bindRoom(params);
            editNameParams = {
              "lockId": _list[_checkIndex]["lockId"],
              "lockName": "${widget.buildingName}${widget.roomName}",
            };
            await lockApi.editLock(editNameParams);
            break;
          case DeviceType.electricityMeter:

          ///电表
            params["id"] = _list[_checkIndex]["electricityMeterId"];
            await electricityMeterApi.bindRoom(params);
            editNameParams = {
              "electricityMeterId": _list[_checkIndex]["electricityMeterId"],
              "name": "${widget.buildingName}${widget.roomName}",
            };
            await electricityMeterApi.editElectricityMeter(editNameParams);
            break;
          case DeviceType.faceLock:

          /// 门禁
            params["faceLockId"] = _list[_checkIndex]["faceLockId"];
            params["roomIds"] = widget.roomId;
            await entranceGuardApi.bindRooms(params);
            break;
        }
        EasyLoading.dismiss();
        Stacker.pop(true);
      }
    );
  }

  @override
  void initState() {
    _getUnbindList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: _title(),
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      showSearch: false,
      showFloatBtn: false,
      actions: [
        TextButton(
          child: Text("保存", style: TextStyle(color: Colors.white),),
          onPressed: () {
            print(widget.roomName);
            if (_checkIndex == -1) {
              EasyLoading.showToast("请选择设备");
            } else {
              _bindDevice();
            }
          },
        )
      ],
      children: [
        Container(
          padding: EdgeInsets.only(top: 60, bottom: 78),
          child: _list.isEmpty
              ? EmptyData()
              : ListView.separated(
                  itemBuilder: (context, index) {
                    return Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                      decoration: const BoxDecoration(
                        color: Colors.white,
                      ),
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          setState(() {
                            _checkIndex = _checkIndex == index ? -1 : index;
                          });
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(_name(_list[index])),
                            _checkIndex == index
                                ? const Icon(Icons.check_circle, color: ThemeVars.colorPrimary,)
                                : const Icon(Icons.circle_outlined, color: ThemeVars.colorPrimary,)
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const SolidDivider(padding: EdgeInsets.only(left: 12)),
                  itemCount: _list.length
              ),
        ),
        Positioned(
            width: MediaQuery.of(context).size.width,
            top: 0,
            left: 0,
            child: Container(
                width: MediaQuery.of(context).size.width,
                decoration: const BoxDecoration(
                  color: ThemeVars.colorBackground,
                ),
                child: Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                      decoration: const BoxDecoration(
                          color: Colors.white
                      ),
                      child: SizedBox(
                        height: 40,
                        child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(5)),
                                borderSide: BorderSide.none
                            ),
                            hintText: "请输入智能设备名称",
                            isDense: true,
                            filled: true,
                            fillColor: ThemeVars.colorBackground,
                            suffixIcon: SizedBox(
                              child: Icon(Icons.search, size: 20,),
                            ),
                          ),
                          style: const TextStyle(fontSize: 14),
                          onSubmitted: (value) {
                            print("object$value");
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 10, child: DecoratedBox(decoration: BoxDecoration(color: ThemeVars.colorBackground)),)
                  ],
                )
            )
        ),
        // Positioned(
        //     bottom: 0,
        //     left: 0,
        //     width: MediaQuery.of(context).size.width,
        //     child: Container(
        //       padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
        //       decoration: const BoxDecoration(
        //           color: Colors.white,
        //           boxShadow: [ThemeVars.boxShadow]
        //       ),
        //       child: Button(
        //           type: ButtonType.primary,
        //           onPressed: () {},
        //           child: Text(_public() ? "管理" : "解除关联")
        //       ),
        //     )
        // ),
      ],
    );
  }

}